package com.byr.byrplayer;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.byr.network.ConnectionServer;
import com.byr.tools.RecommendAdapter;
import com.byr.tools.TvListAdapter;
import com.darrenmowat.imageloader.library.NetworkImageView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class FirstFragment extends Fragment{
	
	static MainpageActivity parent;
	private ViewPager adViewPager;
	private LinearLayout pagerLayout;
	private List<View> pageViews;
	private  ImageView[] imageViews;
	private ImageView imageView;
	private  static AdPageAdapter adapter = null;
	private AtomicInteger atomicInteger = new AtomicInteger(0);  
    private boolean isContinue = true; 
    private boolean running = false;
    private static boolean adinited = false;
    public static Handler handler;
    public static RecommendAdapter recommendAdapter = null;
    PullToRefreshScrollView mPullRefreshScrollView;
	//public MyListView list;
    public View adview;
    View fv;
    private Bitmap[] adPics;  //the picture of the Bitmap
    
	public FirstFragment(MainpageActivity m){
		parent = m;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		fv = inflater.inflate(R.layout.fragment_first, null); 
		adview = fv.findViewById(R.id.view_pager_content);
		ListView listView =(ListView)fv.findViewById(R.id.list);
		recommendAdapter = new RecommendAdapter(MainpageActivity.databaseHelper.getAllRecommend(),parent);
		listView.setAdapter(recommendAdapter);
		listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int arg2,
					long arg3) {
				Intent intent = new Intent(parent,VideoActivity.class);
        		Bundle bundle=new Bundle();  
        		TextView urlText = (TextView)v.findViewById(R.id.url);
				String url =urlText.getText().toString();
        		bundle.putString("url",url);  
        		intent.putExtras(bundle);  
        		startActivity(intent);
			}
			
		});
        initViewPager();
        adinited = true;
        handler = new Handler() {  
            @Override  
            public void handleMessage(Message msg) {  
                if (msg.what == 1) {  
                	
                }else if (msg.what == -1) {  
                	showToask("电台更新成功，Byrer们祝你有个好心情");
                }else if (msg.what == -2) {  
                	showToask("一会儿再试吧，没有收到数据呢。。。");
                }else if(msg.what == -10){
                	changePageAdapter();
                }else if(msg.what == -11){
                	actuallyChangeAdapter();
                }
                
            }  
        };  
        mPullRefreshScrollView = (PullToRefreshScrollView) fv.findViewById(R.id.pull_refresh_scrollview);
		mPullRefreshScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				new GetDataTask().execute();
			}
		});
		return fv;
	}
	
	private class GetDataTask extends AsyncTask<Void, Void, String[]> {

		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			try {
				MainpageActivity.tvadrefreshed = false;
				new Thread(){
					public void run(){
						ConnectionServer.requireAd();
						ConnectionServer.requireTvUpdate();
						ConnectionServer.requireRecommend();
					}
				}.start();
				for(int i = 0;i < 40 && MainpageActivity.tvadrefreshed == false;i++)
					Thread.sleep(100);
				if(MainpageActivity.tvadrefreshed){
					Message msg = new Message();  
    	            msg.what = -3;  
    	            MainpageActivity.handler.sendMessage(msg);  
				}else{
					Message msg = new Message();  
    	            msg.what = -2;  
    	            MainpageActivity.handler.sendMessage(msg); 
				}
			} catch (InterruptedException e) {
			}
			return null;
		}

		@Override
		protected void onPostExecute(String[] result) {
			// Do some stuff here

			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshScrollView.onRefreshComplete();

			super.onPostExecute(result);
		}
	}
	
	void showToask(String hint) {
		Toast toast = Toast.makeText(parent, hint, Toast.LENGTH_SHORT);
		toast.show();
	}
	private void initViewPager() {

		//浠庡竷灞�枃浠朵腑鑾峰彇ViewPager鐖跺鍣�
		pagerLayout = (LinearLayout) fv.findViewById(R.id.view_pager_content);
		//鍒涘缓ViewPager
    	adViewPager = new ViewPager(parent);
    	adViewPager.setOffscreenPageLimit(6);
    	
    	//鑾峰彇灞忓箷鍍忕礌鐩稿叧淇℃伅
    	DisplayMetrics dm = new DisplayMetrics();
    	parent.getWindowManager().getDefaultDisplay().getMetrics(dm);
    	
        //鏍规嵁灞忓箷淇℃伅璁剧疆ViewPager骞垮憡瀹瑰櫒鐨勫楂�
        adViewPager.setLayoutParams(new LayoutParams(dm.widthPixels, dm.heightPixels * 2 / 5));
        
        //灏哣iewPager瀹瑰櫒璁剧疆鍒板竷灞�枃浠剁埗瀹瑰櫒涓�
    	pagerLayout.addView(adViewPager);
    	initPageAdapter();
    	
    	initCirclePoint();
    	
    	adViewPager.setAdapter(adapter);
    	adViewPager.setOnPageChangeListener(new AdPageChangeListener());
    	if(!running){
    		running = true;
    		new Thread(new Runnable() {  
            	@Override  
            	public void run() {  
                	while (true) {  
                    	if (isContinue) {  
                        	viewHandler.sendEmptyMessage(atomicInteger.get());  
                        	atomicOption();  
                    	}  
                	}  
            	}  
        	}).start();  
    	}
	}
	
	
    private void atomicOption() {  
        atomicInteger.incrementAndGet();  
        if (atomicInteger.get() > imageViews.length - 1) {  
        	atomicInteger.getAndAdd(-5);  
        }  
        try {  
            Thread.sleep(3000);  
        } catch (InterruptedException e) {  
              
        }  
    } 
	
    /*
     * 姣忛殧鍥哄畾鏃堕棿鍒囨崲骞垮憡鏍忓浘鐗�
     */
    @SuppressLint("HandlerLeak")
	private final Handler viewHandler = new Handler() {  
  
        @Override  
        public void handleMessage(Message msg) {  
        	adViewPager.setCurrentItem(msg.what);  
            super.handleMessage(msg);  
        }  
  
    }; 
	
	private void initPageAdapter() {
		pageViews = new ArrayList<View>();
		
		final ImageView img1 = new ImageView(parent);  
        img1.setBackgroundResource(R.drawable.view_add_1);  
		pageViews.add(img1);  
        
        ImageView img2 = new ImageView(parent);  
        img2.setBackgroundResource(R.drawable.view_add_2);  
        pageViews.add(img2); 
        
        ImageView img3 = new ImageView(parent);  
        img3.setBackgroundResource(R.drawable.view_add_3);  
        pageViews.add(img3); 
        
        ImageView img4 = new ImageView(parent);  
        img4.setBackgroundResource(R.drawable.view_add_4);  
        pageViews.add(img4); 
        
        ImageView img5 = new ImageView(parent);  
        img5.setBackgroundResource(R.drawable.view_add_5);  
        pageViews.add(img5); 
        
        ImageView img6 = new ImageView(parent);  
        img6.setBackgroundResource(R.drawable.view_add_6);  
        pageViews.add(img6);  
        
        adapter = new AdPageAdapter(pageViews);
	}
	
	public void changePageAdapter() {
		 
		
		while(!adinited){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		adPics = new Bitmap[6];
		new Thread(){
			public void run(){
				try{
					/*adPics[0] = getHttpBitmap(MainpageActivity.addUrl[0]);
					adPics[1] = getHttpBitmap(MainpageActivity.addUrl[1]);
					adPics[2] = getHttpBitmap(MainpageActivity.addUrl[2]);
					adPics[3] = getHttpBitmap(MainpageActivity.addUrl[3]);
					adPics[4] = getHttpBitmap(MainpageActivity.addUrl[4]);
					adPics[5] = getHttpBitmap(MainpageActivity.addUrl[5]);*/
					Message msg = new Message();  
    	            msg.what = -11;  
    	            FirstFragment.handler.sendMessage(msg);  
				}catch(Exception e){
				
				}
			}
		}.start();
	}
	
	public void actuallyChangeAdapter(){
		pageViews = new ArrayList<View>();
		
		 NetworkImageView img1 = new NetworkImageView(parent);  
		 NetworkImageView img2 = new NetworkImageView(parent);  
		 NetworkImageView img3 = new NetworkImageView(parent);  
		 NetworkImageView img4 = new NetworkImageView(parent);  
		 NetworkImageView img5 = new NetworkImageView(parent);  
		 NetworkImageView img6 = new NetworkImageView(parent); 
		
		img1.setImageUrl(MainpageActivity.addUrl[0],(Activity)parent);
		img2.setImageUrl(MainpageActivity.addUrl[1],(Activity)parent);
		img3.setImageUrl(MainpageActivity.addUrl[2],(Activity)parent);
		img4.setImageUrl(MainpageActivity.addUrl[3],(Activity)parent);
		img5.setImageUrl(MainpageActivity.addUrl[4],(Activity)parent);
		img6.setImageUrl(MainpageActivity.addUrl[5],(Activity)parent);
		
		/*img2.setImageBitmap(adPics[1]);
		img3.setImageBitmap(adPics[2]);
		img4.setImageBitmap(adPics[3]);
		img5.setImageBitmap(adPics[4]);
		img6.setImageBitmap(adPics[5]);
		*/
		img1.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(MainpageActivity.adIsVideo != null){
					if( !MainpageActivity.adIsVideo[0]){
						Intent intent = new Intent();        
						intent.setAction("android.intent.action.VIEW");    
						Uri content_url = Uri.parse(MainpageActivity.adContent[0]);   
						intent.setData(content_url);  
						if(MainpageActivity.adContent[0] != null)
							try{
								startActivity(intent);
							}catch(Exception e){
								Message msg = new Message();  
		        	            msg.what = -4;  
		        	            MainpageActivity.handler.sendMessage(msg);  
							}
					}else{
						Intent intent = new Intent(parent,VideoActivity.class);
		        		Bundle bundle=new Bundle();  
						String url = MainpageActivity.adContent[0];
		        		bundle.putString("url",url);  
		        		intent.putExtras(bundle);  
		        		startActivity(intent);
					}
				}
			}
			
		});
		img2.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(MainpageActivity.adIsVideo != null){
					if( !MainpageActivity.adIsVideo[1]){
						Intent intent = new Intent();        
						intent.setAction("android.intent.action.VIEW");    
						Uri content_url = Uri.parse(MainpageActivity.adContent[1]);   
						intent.setData(content_url);  
						if(MainpageActivity.adContent[1] != null)
							try{
								startActivity(intent);
							}catch(Exception e){
								Message msg = new Message();  
		        	            msg.what = -4;  
		        	            MainpageActivity.handler.sendMessage(msg);  
							}
					}else{
						Intent intent = new Intent(parent,VideoActivity.class);
		        		Bundle bundle=new Bundle();  
						String url = MainpageActivity.adContent[1];
		        		bundle.putString("url",url);  
		        		intent.putExtras(bundle);  
		        		startActivity(intent);
					}
				}
			}
			
		});
		img3.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(MainpageActivity.adIsVideo != null){
					if( !MainpageActivity.adIsVideo[2]){
						Intent intent = new Intent();        
						intent.setAction("android.intent.action.VIEW");    
						Uri content_url = Uri.parse(MainpageActivity.adContent[2]);   
						intent.setData(content_url);  
						if(MainpageActivity.adContent[2] != null)
							try{
								startActivity(intent);
							}catch(Exception e){
								Message msg = new Message();  
		        	            msg.what = -4;  
		        	            MainpageActivity.handler.sendMessage(msg);  
							}
					}else{
						Intent intent = new Intent(parent,VideoActivity.class);
		        		Bundle bundle=new Bundle();  
						String url = MainpageActivity.adContent[2];
		        		bundle.putString("url",url);  
		        		intent.putExtras(bundle);  
		        		startActivity(intent);
					}
				}
			}
			
		});
		img4.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(MainpageActivity.adIsVideo != null){
						if( !MainpageActivity.adIsVideo[3]){
						Intent intent = new Intent();        
						intent.setAction("android.intent.action.VIEW");    
						Uri content_url = Uri.parse(MainpageActivity.adContent[3]);   
						intent.setData(content_url);  
						if(MainpageActivity.adContent[3] != null)
							try{
								startActivity(intent);
							}catch(Exception e){
								Message msg = new Message();  
		        	            msg.what = -4;  
		        	            MainpageActivity.handler.sendMessage(msg);  
							}
					}else{
						Intent intent = new Intent(parent,VideoActivity.class);
		        		Bundle bundle=new Bundle();  
						String url = MainpageActivity.adContent[3];
		        		bundle.putString("url",url);  
		        		intent.putExtras(bundle);  
		        		startActivity(intent);
					}
				}
			}
			
		});
		img5.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(MainpageActivity.adIsVideo != null){
					if( !MainpageActivity.adIsVideo[4]){
						Intent intent = new Intent();        
						intent.setAction("android.intent.action.VIEW");    
						Uri content_url = Uri.parse(MainpageActivity.adContent[4]);   
						intent.setData(content_url);  
						if(MainpageActivity.adContent[4] != null)
							try{
								startActivity(intent);
							}catch(Exception e){
								Message msg = new Message();  
		        	            msg.what = -4;  
		        	            MainpageActivity.handler.sendMessage(msg);  
							}
					}else{
						Intent intent = new Intent(parent,VideoActivity.class);
		        		Bundle bundle=new Bundle();  
						String url = MainpageActivity.adContent[4];
		        		bundle.putString("url",url);  
		        		intent.putExtras(bundle);  
		        		startActivity(intent);
					}
				}
			}
			
		});
		img6.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(MainpageActivity.adIsVideo != null){
					if( !MainpageActivity.adIsVideo[5]){
						Intent intent = new Intent();        
						intent.setAction("android.intent.action.VIEW");    
						Uri content_url = Uri.parse(MainpageActivity.adContent[5]);   
						intent.setData(content_url);  
						if(MainpageActivity.adContent[5] != null)
							try{
								startActivity(intent);
							}catch(Exception e){
								Message msg = new Message();  
		        	            msg.what = -4;  
		        	            MainpageActivity.handler.sendMessage(msg);  
							}
					}else{
						Intent intent = new Intent(parent,VideoActivity.class);
		        		Bundle bundle=new Bundle();  
						String url = MainpageActivity.adContent[5];
		        		bundle.putString("url",url);  
		        		intent.putExtras(bundle);  
		        		startActivity(intent);
					}
				}
			}
			
		});
		
		pageViews.add(img1);
		pageViews.add(img2);
		pageViews.add(img3);
		pageViews.add(img4);
		pageViews.add(img5);
		pageViews.add(img6);  
        try{
        	adapter = new AdPageAdapter(pageViews);
        	adViewPager.setAdapter(adapter);
        	adViewPager.setOffscreenPageLimit(6);
        	initCirclePoint();
		}catch(Exception e){Log.d("netlink","failed++"+e.toString());}
	}
	private void initCirclePoint(){
		ViewGroup group = (ViewGroup) fv.findViewById(R.id.viewGroup); 
        imageViews = new ImageView[pageViews.size()];  
        group.removeAllViews();
        //骞垮憡鏍忕殑灏忓渾鐐瑰浘鏍�
        for (int i = 0; i < pageViews.size(); i++) {  
        	//鍒涘缓涓�釜ImageView, 骞惰缃楂� 灏嗚瀵硅薄鏀惧叆鍒版暟缁勪腑
        	imageView = new ImageView(parent);  
            imageView.setLayoutParams(new LayoutParams(10,10));  
            imageViews[i] = imageView;  
            
            //鍒濆鍊� 榛樿绗�涓�涓�
            if (i == 0) {  
                imageViews[i]  
                        .setBackgroundResource(R.drawable.point_focused);  
            } else {  
                imageViews[i]  
                        .setBackgroundResource(R.drawable.point_unfocused);  
            }  
            //灏嗗皬鍦嗙偣鏀惧叆鍒板竷灞�腑
            
            group.addView(imageViews[i]);  
        } 
	}
	
	/**
	 *	ViewPager 椤甸潰鏀瑰彉鐩戝惉鍣�
	 */
    private final class AdPageChangeListener implements OnPageChangeListener {  
    	
    	/**
    	 * 椤甸潰婊氬姩鐘舵�鍙戠敓鏀瑰彉鐨勬椂鍊欒Е鍙�
    	 */
        @Override  
        public void onPageScrollStateChanged(int arg0) {  
        }  
  
        /**
         * 椤甸潰婊氬姩鐨勬椂鍊欒Е鍙�
         */
        @Override  
        public void onPageScrolled(int arg0, float arg1, int arg2) {  
        }  
  
        /**
         * 椤甸潰閫変腑鐨勬椂鍊欒Е鍙�
         */
        @Override  
        public void onPageSelected(int arg0) {  
        	//鑾峰彇褰撳墠鏄剧ず鐨勯〉闈㈡槸鍝釜椤甸潰
            atomicInteger.getAndSet(arg0);  
            //閲嶆柊璁剧疆鍘熺偣甯冨眬闆嗗悎
            for (int i = 0; i < imageViews.length; i++) {  
                imageViews[arg0]  
                        .setBackgroundResource(R.drawable.point_focused);  
                if (arg0 != i) {  
                    imageViews[i]  
                            .setBackgroundResource(R.drawable.point_unfocused);  
                }  
            }  
            if(arg0 == 0){
            	Message msg = new Message();  
	            msg.what = 11;  
	            MainpageActivity.handler.sendMessage(msg);  
            }else{
            	Message msg = new Message();  
	            msg.what = 10;  
	            MainpageActivity.handler.sendMessage(msg);  
            }
        }  
    } 
	
	
    private final class AdPageAdapter extends PagerAdapter {  
        private List<View> views = null;  
  
        /**
         * 鍒濆鍖栨暟鎹簮, 鍗砎iew鏁扮粍
         */
        public AdPageAdapter(List<View> views) {  
            this.views = views;  
        }  
        
        /**
         * 浠嶸iewPager涓垹闄ら泦鍚堜腑瀵瑰簲绱㈠紩鐨刅iew瀵硅薄
         */
        @Override  
        public void destroyItem(View container, int position, Object object) {  
            ((ViewPager) container).removeView(views.get(position));  
        }  
  
        /**
         * 鑾峰彇ViewPager鐨勪釜鏁�
         */
        @Override  
        public int getCount() {  
            return views.size();  
        }  
  
        /**
         * 浠嶸iew闆嗗悎涓幏鍙栧搴旂储寮曠殑鍏冪礌, 骞舵坊鍔犲埌ViewPager涓�
         */
        @Override  
        public Object instantiateItem(View container, int position) {  
            ((ViewPager) container).addView(views.get(position), 0);  
            return views.get(position);  
        }  
  
        /**
         * 鏄惁灏嗘樉绀虹殑ViewPager椤甸潰涓巌nstantiateItem杩斿洖鐨勫璞¤繘琛屽叧鑱�
         * 杩欎釜鏂规硶鏄繀椤诲疄鐜扮殑
         */
        @Override  
        public boolean isViewFromObject(View view, Object object) {  
            return view == object;  
        }  
    }
    
   
        /**
         * 获取网落图片资源 
         * @param url
         * @return
         */
        public static Bitmap getHttpBitmap(String url){
        	URL myFileURL;
        	Bitmap bitmap=null;
        	try{
        		myFileURL = new URL(url);
        		//获得连接
        		HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
        		//设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
        		conn.setConnectTimeout(6000);
        		//连接设置获得数据流
        		conn.setDoInput(true);
        		//不使用缓存
        		conn.setUseCaches(false);
        		//这句可有可无，没有影响
        		
        		//conn.connect();
        		//得到数据流
        		InputStream is = conn.getInputStream();
        		//解析得到图片
        		Log.d("byrimage","success");
        		bitmap = BitmapFactory.decodeStream(is);
        		//关闭数据流
        		is.close();
        		
        	}catch(Exception e){
        		e.printStackTrace();
        		Log.d("byrimage","error when loading bitmap"+e.toString());
        	}
        	
    		return bitmap;
        	
        }
       
}
